<?php


namespace App\Http\Controllers\Api;
use App\Models\Car;
use App\Models\Config;
use App\Services\CarService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redis;

class CarController extends BaseController
{

    public function flow(Request $request) {
        $this->_check();
        $this->validate($request, [
            'car_id' => 'required',
            'status' => 'required|in:1,2,3',
        ]);
        $input = $request->input();
        $user = $this->getUser();
        $from = '1';
        try {
            CarService::flow($input, $user->id, $from, $user);
            return $this->success([]);
        } catch (\Exception $e) {
            if ($e->getCode() != 200) {
                \Log::error($e);
            }
            return $this->failed($e->getMessage());
        }
    }

    public function cancel(Request $request) {
        $this->_check();
        $this->validate($request, [
            'car_id' => 'required',
        ]);
        $car_id = $request->input('car_id');
        $car = Car::find($car_id);
        if (!$car)
            return $this->failed('车不存在');

        if ($car->status != Car::STATUS_WAIT_APPOINT) {
            return $this->failed('只允许待预约状态取消操作');
        }

        $user = $this->getUser();
        $car->cancel_user_id = $user->id;
        $car->status = Car::STATUS_CANCEL;
        $car->cancel_at = date('Y-m-d H:i:s');
        $car->save();
        return $this->success(['id' => $car_id], "取消成功");
    }

    public function index(Request $request) {
        $this->_check();
        $user = $this->getUser();
        $request->role = $user->role;
        $request->title = $user->title;
        $request->from = 'api';
        $step = $request->input('step');
        if ($step == 'appoint') {
//            $request->status = '0, 1, 5'; // 0：带预约, 1：预约，2:签到，3：签退 , 4：发送进场通知，5：取消
            $appoint = Config::getAppointTime();

            $date = $appoint['val'];
            $request->type = 1;
            $request->date = $date;
            $request->queue_num_show = $appoint['queue_num_show'];

        } else if($step == 'loan') {
            $request->status = '1, 2, 3, 4';
            $loan = Config::isShowLoad();
            $date = $loan['val'];
            $request->type = 1;
            $request->date = $date;
        }
        $list = CarService::search_list($request);
        return $this->paginate($list);
    }

    public function info(Request $request) {
        $this->validate($request, [
            'car_id' => 'required',
        ]);
        $car_id = \request('car_id');
        $car = Car::find($car_id);
        if (!$car)
            return $this->failed('车辆不存在');
        return $this->success($car);

    }
}

